package org.john.auth.server.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.google.common.cache.Cache;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class LocalCacheService {

	@Autowired
	private Cache<String, Object> guavaLocalCache;

	public <E> E get(String key, Class<E> clazz) {
		Object object = guavaLocalCache.getIfPresent(key);
		log.info("LocalCache.get() key={}, clazz={}", key, clazz.getName());
		return object == null ? null : (E) object;
	}

	public List<String> getAll() {
		List<String> result = new ArrayList<>();
		Set<String> keys = keys();
		if (keys.isEmpty()) {
			Map<String, Object> resultMap = guavaLocalCache.getAllPresent(keys);
			if (!resultMap.isEmpty()) {
				for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
					result.add(entry.getKey() + ":" + entry.getValue());
				}
			}
		}
		log.info("LocalCache.getAll()");
		return result;
	}

	public <E> List<Long> put(String key, E value) {
		guavaLocalCache.put(key, value);
		log.info("LocalCache.put() key={}, clazz={}", key, value);
		return null;
	}

	public void remove(String... keys) {
		if (ArrayUtils.isNotEmpty(keys)) {
			List<String> keyList = (List<String>) CollectionUtils.arrayToList(keys);
			guavaLocalCache.invalidateAll(keyList);
		}
		log.info("LocalCache.remove() keys={}", keys);
	}

	public void clean() {
		guavaLocalCache.invalidateAll();
	}

	private Set<String> keys() {
		return guavaLocalCache.asMap().keySet();
	}
}
